package org.fight.landowner.remoting.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.fight.landowner.common.constant.CommonConstant;
import org.fight.landowner.remoting.protocol.RemotingCommandHeader;
import org.fight.landowner.remoting.protocol.RemotingSerializableUtil;

import java.util.List;

/**
 * @Author wangxuehao02
 * @Date 2024/2/3 12:54 AM
 * @Description
 * 解码器
 *
 * maxFrameLength – 帧的最大长度。 如果帧的长度大于该值，将抛出 TooLongFrameException。
 * lengthFieldOffset – 帧长度的起始位置
 * lengthFieldLength – 帧的长度所占的字节数
 * lengthAdjustment – 添加到长度字段值的补偿值 todo 该字段含义
 * initialBytesToStrip – 丢弃的起始字节数
 **/

@Slf4j
public class NettyDecoder extends LengthFieldBasedFrameDecoder {
    public NettyDecoder() {
        super(8388608, 0, 4, 0, 4);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;

        try {
            frame = (ByteBuf) super.decode(ctx, in);

            if (frame == null) {
                return null;
            }

            return RemotingSerializableUtil.deSerialize(frame.nioBuffer());
        } catch (Exception e) {
            log.error("NettyDecoder byteBuf decode error = {}", e);
        } finally {
            if (frame != null) {
                frame.release();
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
//        int init = 1;
//
//        for (int i = 0; i < 32; i++) {
//            System.out.println(init *= 2);
//        }
        NettyDecoder nettyDecoder = new NettyDecoder();

        ByteBuf buffer = Unpooled.buffer(100);

        buffer.writeInt(96);

        for (byte i = 0; i < 96; i++) {
            buffer.writeByte(i);
        }

        ByteBuf decodeByteBuf = (ByteBuf) nettyDecoder.decode(null, buffer);
//        byte[] array = decodeByteBuf.array();

        for (int i = 0; i < 96; i++) {
            System.out.println(decodeByteBuf.readByte());
        }


//        for (byte b : array) {
//            System.out.print(b + "\t");
//        }

    }
}
